package com.zheng.oa.admin.controller.wc;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zheng.common.base.BaseController;
import com.zheng.common.util.HtmlUtil;
import com.zheng.common.util.Pagination;
import com.zheng.common.util.PoiUtil;
import com.zheng.common.util.TimeUtil;
import com.zheng.oa.common.constant.OaResult;
import com.zheng.oa.common.constant.OaResultConstant;
import com.zheng.oa.common.constant.enums.OaStatus;
import com.zheng.oa.common.constant.enums.PlanTimeType;
import com.zheng.upms.dao.model.UpmsOrganization;
import com.zheng.upms.dao.model.UpmsUser;
import com.zheng.upms.rpc.api.UpmsApiService;
import com.zheng.upms.rpc.api.UpmsOrganizationService;
import com.zheng.upms.rpc.api.UpmsUserService;
import com.zheng.wc.dao.model.WcPersonalPlan;
import com.zheng.wc.rpc.api.WcPersonalPlanService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: xinqi
 * Date: 2018/3/30
 * Time: 9:28
 */
@Controller
@Api(value = "个人月计划管理", description = "个人月计划管理")
@RequestMapping("/oa/wc/personalMonthPlan")
public class WcPersonalMonthPlanController extends BaseController {
    @Autowired
    private WcPersonalPlanService personalPlanService;
    @Autowired
    private UpmsUserService upmsUserService;
    @Autowired
    private UpmsOrganizationService organizationService;
    @Autowired
    private UpmsApiService apiService;

    @ApiOperation(value = "个人月计划管理")
    @RequiresPermissions("oa:wc:personalMonthPlan:read")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model) {
        return "/manage/wc/personalMonthPlan/index.jsp";
    }

    @ApiOperation(value = "个人月计划列表")
    @RequiresPermissions("oa:wc:personalMonthPlan:read")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Object list(@RequestParam(required = false, defaultValue = "1", value = "pageNumber") int pageNumber,
                       @RequestParam(required = false, defaultValue = "10", value = "pageSize") int pageSize,
                       @RequestParam(required = false, value = "sortName") String sortName,
                       @RequestParam(required = false, value = "sortOrder") String sortOrder,
                       WcPersonalPlan personalPlan) {
        personalPlan.setPagination(new Pagination(pageNumber, pageSize, sortOrder, sortName));
        personalPlan.setTimeType(PlanTimeType.MONTH_PLAN.getKey());
        personalPlan.setStatus(OaStatus.NORMAL.getKey());
        personalPlan.getSqlMap().put("sql",apiService.sqlDataScopeFilter(getUsername(), "wpp", "uu"));
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> rows = personalPlanService.selectPersonalPlanPage(personalPlan);
        Integer total = personalPlanService.selectPersonalPlanPageCount(personalPlan);
        result.put("rows", rows);
        result.put("total", total);
        return result;
    }

    @ApiOperation(value = "新增个人月计划")
    @RequiresPermissions("oa:wc:personalMonthPlan:create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(Model model) {
        LocalDate now = LocalDate.now();
        int year = now.getYear();
        int month = now.getMonthValue();
        model.addAttribute("year", year);
        model.addAttribute("month", month);
        return "/manage/wc/personalMonthPlan/create.jsp";
    }

    @ApiOperation(value = "新增个人月计划")
    @RequiresPermissions("oa:wc:personalMonthPlan:create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Object create(@RequestBody WcPersonalPlan plan) throws Exception {
        String username = getUsername();
        UpmsUser upmsUser = apiService.selectUpmsUserByUsername(username);
        plan.setCuser(upmsUser.getUserId());
        plan.setCorganization(upmsUser.getOrganizationId());
        plan.setCtime(new Date());
        plan.setReadCount(0);
        plan.setStatus(OaStatus.NORMAL.getKey());
        plan.setTimeType(PlanTimeType.MONTH_PLAN.getKey());
        plan.setPlanDate(TimeUtil.concatDate(plan.getPlanYear(), plan.getPlanMonth()));
        try {
            personalPlanService.insert(plan);
        } catch (Exception e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }

    @ApiOperation(value = "修改个人月计划")
    @RequiresPermissions("oa:wc:personalMonthPlan:update")
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String update(Model model, Integer id) {
        WcPersonalPlan plan = personalPlanService.selectById(id);
        model.addAttribute("plan", plan);
        return "/manage/wc/personalMonthPlan/update.jsp";
    }

    @ApiOperation(value = "修改个人月计划")
    @RequiresPermissions("oa:wc:personalMonthPlan:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object update(@RequestBody WcPersonalPlan plan) throws Exception {
        UpmsUser upmsUser = apiService.selectUpmsUserByUsername(getUsername());
        plan.setPlanDate(TimeUtil.concatDate(plan.getPlanYear(), plan.getPlanMonth()));
        WcPersonalPlan wcPlan = personalPlanService.selectById(plan);
        Integer cUserId = wcPlan.getCuser();
        //只允许自己修改自己
        if (!cUserId.equals(upmsUser.getUserId())) {
            return new OaResult(OaResultConstant.FAILED, "不可以修改他人的工作计划！");
        }
        try {
            personalPlanService.updateById(plan);
        } catch (Exception e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }

    @ApiOperation(value = "删除个人月计划")
    @RequiresPermissions("oa:wc:personalMonthPlan:delete")
    @RequestMapping(value = "/delete/{ids}", method = RequestMethod.GET)
    @ResponseBody
    public Object delete(@PathVariable("ids") String ids) {
        String username = getUsername();
        UpmsUser upmsUser = apiService.selectUpmsUserByUsername(username);

        EntityWrapper<WcPersonalPlan> entityWrapper = new EntityWrapper<>();
        entityWrapper.where("cuser !=" + upmsUser.getUserId());
        entityWrapper.in("id", ids);
        int count = personalPlanService.selectCount(entityWrapper);
        if (count >= 1) {
            return new OaResult(OaResultConstant.FAILED, "不可以删除他人的工作计划！");
        }
        try {
            personalPlanService.deletePlans(ids);
        } catch (Exception e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }

    @ApiOperation(value = "导出个人月计划")
    @RequiresPermissions("oa:wc:personalMonthPlan:export")
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public void export(WcPersonalPlan personalPlan,
                       HttpServletResponse response) throws Exception {
        String title = "个人月度计划";
        String realname = "";
        String dateStr = "";
        String organizationName = "";
        personalPlan.setTimeType(PlanTimeType.MONTH_PLAN.getKey());
        personalPlan.setStatus(OaStatus.NORMAL.getKey());
        personalPlan.getSqlMap().put("sql",apiService.sqlDataScopeFilter(getUsername(), "wpp", "uu"));
        if (personalPlan.getCuser() != null) {
            UpmsUser upmsUser = upmsUserService.selectById(personalPlan.getCuser());
            if (null != upmsUser) {
                realname = upmsUser.getRealname();
            }
        }
        if (personalPlan.getCorganization() != null) {
            UpmsOrganization organization = organizationService.selectById(personalPlan.getCorganization());
            if (null != organization) {
                organizationName = organization.getName();
            }
        }
        if (null != personalPlan.getPlanYear()) {
            dateStr += personalPlan.getPlanYear() + "年";
        }
        if (null != personalPlan.getPlanYear()) {
            dateStr += personalPlan.getPlanYear() + "月";
        }
        title = organizationName + realname + dateStr + title;
        List<Map<String, Object>> plans = personalPlanService.selectPersonalPlanPage(personalPlan);
        for (Map<String, Object> plan : plans) {
            Object planDetailObj = plan.get("planDetail");
            if (null != planDetailObj) {
                String planDetail = HtmlUtil.delHTMLTag(planDetailObj.toString());
                plan.put("planDetail", planDetail);
            }
        }
        List<ExcelExportEntity> entities = new ArrayList<>();
        ExcelExportEntity entity = new ExcelExportEntity();
        entity.setKey("planName");
        entity.setName("计划名称");
        entities.add(entity);
        entity = new ExcelExportEntity();
        entity.setKey("planDetail");
        entity.setName("计划详情");
        entities.add(entity);
        entity = new ExcelExportEntity();
        entity.setKey("organizationName");
        entity.setName("工作部门");
        entities.add(entity);
        entity = new ExcelExportEntity();
        entity.setKey("planYear");
        entity.setName("计划年份");
        entities.add(entity);
        entity = new ExcelExportEntity();
        entity.setKey("planMonth");
        entity.setName("计划月份");
        entities.add(entity);
        entity = new ExcelExportEntity();
        entity.setKey("remark");
        entity.setName("备注");
        entities.add(entity);
        entity = new ExcelExportEntity();
        entity.setKey("username");
        entity.setName("计划人姓名");
        entities.add(entity);
        PoiUtil.export(response, plans, entities, title);
    }

    @RequiresPermissions("oa:wc:personalMonthPlan:import")
    @RequestMapping(value = "/import", method = RequestMethod.GET)
    public String doImport() {
        return "/manage/wc/personalMonthPlan/import.jsp";
    }

    @RequiresPermissions("oa:wc:personalMonthPlan:import")
    @ResponseBody
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public Object doImport(@RequestParam("file") MultipartFile file) {
        ImportParams params = new ImportParams();
        UpmsUser upmsUser = apiService.selectUpmsUserByUsername(getUsername());
        JSONObject data = new JSONObject();
        try {
            List<Map<String, Object>> maps = ExcelImportUtil.importExcel(file.getInputStream(), Map.class, params);
            JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(maps));
            JSONArray planArray = new JSONArray();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String planName = jsonObject.getString("计划名称");
                String planYear = jsonObject.getString("计划年份");
                String planMonth = jsonObject.getString("计划月份");
                if (StringUtils.isBlank(planName)) {
                    continue;
                }
                if (StringUtils.isBlank(planYear)) {
                    continue;
                }
                if (StringUtils.isBlank(planMonth)) {
                    continue;
                }
                jsonObject.put("planName", planName);
                jsonObject.put("planDetail", jsonObject.getString("计划详情"));
                jsonObject.put("planYear", planYear);
                jsonObject.put("planMonth", planMonth);
                jsonObject.put("remark", jsonObject.getString("备注"));
                jsonObject.put("status", OaStatus.NORMAL.getKey());
                jsonObject.put("timeType", PlanTimeType.MONTH_PLAN.getKey());
                jsonObject.put("ctime", new Date());
                jsonObject.put("cuserId", upmsUser.getUserId());
                planArray.add(jsonObject);
            }
            List<WcPersonalPlan> plans = planArray.toJavaList(WcPersonalPlan.class);
            for(WcPersonalPlan plan:plans){
                plan.setPlanDate(TimeUtil.concatDate(plan.getPlanYear(),plan.getPlanMonth()));
            }
            data.put("count", plans.size());
            if (plans.size() > 0) {
                personalPlanService.insertBatch(plans);
            }
        } catch (Exception e) {
            return new OaResult(OaResultConstant.FAILED, "导入失败");
        }
        return new OaResult(OaResultConstant.SUCCESS, data);
    }

    @ApiOperation(value = "阅读月计划")
    @RequiresPermissions("oa:wc:personalMonthPlan:read")
    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public String view(Integer id, Model model) {
        Map<String, Object> map = personalPlanService.selectPersonalPlan(id);
        WcPersonalPlan personalPlan = new WcPersonalPlan();
        personalPlan.setId(id);
        Integer readCount = Integer.parseInt(map.getOrDefault("readCount", 0).toString());
        readCount = readCount + 1;
        personalPlan.setReadCount(readCount);
        map.put("readCount", readCount);
        personalPlanService.updateById(personalPlan);
        model.addAttribute("plan", JSON.toJSON(map));
        return "/manage/wc/personalMonthPlan/view.jsp";
    }

}
